package com.chenjt.springai.ten_multiModal.controller;

import com.chenjt.springai.ten_multiModal.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.content.Media;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2025/6/2 16:01
 */
@RequiredArgsConstructor // 有参构造
@RestController
@RequestMapping("/ai")
public class MultiModalChatController {

    private final ChatClient multiModalChatClient;

    private final ChatHistoryRepository chatHistoryRepository;


    /**
     * 流式调用
     * @param prompt
     * @return
     */
    @RequestMapping(value = "/streamChat", produces = "text/html;charset=utf-8")
    public Flux<String> streamChat(
            @RequestParam("prompt") String prompt,
            @RequestParam("chatId") String chatId,
            @RequestParam(value = "files",required = false) List<MultipartFile> files
            ){
        //1.保存会话id
        chatHistoryRepository.save("chat",chatId);
        //2.请求模型
        if(files == null || files.isEmpty()){
            // 没有附件，纯文本聊天
            return textChat(prompt,chatId);

        }else{
            // 有附件，多模态聊天
            return multiModalChat(prompt,chatId,files);
        }



    }

    private Flux<String> multiModalChat(String prompt, String chatId, List<MultipartFile> files) {
        // 1.解析多媒体
        List<Media> medias = files.stream()
                .map(file -> new Media(
                        MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                        file.getResource()
                ))
                .toList();

        return multiModalChatClient.prompt()
                .user(p->p.text(prompt).media(medias.toArray(Media[]::new)))
                // 将chatId访问，隔离所有的聊天窗口记忆
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()// 流式调用
                .content();
    }


    private Flux<String> textChat(String prompt, String chatId) {

        return multiModalChatClient.prompt()
                .user(prompt)
                // 将chatId访问，隔离所有的聊天窗口记忆
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()// 流式调用
                .content();
    }


}
